<style scoped>
.icon {
  cursor: pointer;
}
.icon:hover {
  color: #409eff;
}
.category-list-data-table /deep/ .el-table th {
  color: #555;
}
.category-list-data-table{
  height: calc(100vh - 280px);
}
.category-list-data-table /deep/ .vxe-header--row th,.category-list-data-table /deep/ .vxe-body--row td {
  color: #555;
  background:#FFFFFF;
  border-bottom: 1px solid #e9e9e9;
}
.emptynote{
  color: #909399;
  line-height: 60px;
}
/*滚动条整体部分*/
.mytable-scrollbar ::-webkit-scrollbar {
  width: 10px;
  height: 10px;
}
/*滚动条的轨道*/
.mytable-scrollbar ::-webkit-scrollbar-track {
  background-color: #FFFFFF;
}
/*滚动条里面的小方块，能向上向下移动*/
.mytable-scrollbar ::-webkit-scrollbar-thumb {
  background-color: #bfbfbf;
  border-radius: 5px;
  border: 1px solid #F1F1F1;
  box-shadow: inset 0 0 6px rgba(0,0,0,.3);
}
.mytable-scrollbar ::-webkit-scrollbar-thumb:hover {
  background-color: #A8A8A8;
}
.mytable-scrollbar ::-webkit-scrollbar-thumb:active {
  background-color: #787878;
}
/*边角，即两个滚动条的交汇处*/
.mytable-scrollbar ::-webkit-scrollbar-corner {
  background-color: #FFFFFF;
}
</style>
<!--  -->
<template>
  <div class="category-list-data-table">
    <vxe-table
      :data="tableData" :loading="loading" show-overflow max-height="auto" border="inner" class="mytable-scrollbar">
      <vxe-column field="name" title="分类名称">
        <template #default="{ row }">
          <i :class="'noselect icon iconfont ' + showIcon(row.id, row._index)"
            @click.stop="tiggleChildren(row.id)"
            :style="'margin-left: '+rowMaringLeft(row._index)+'px'"></i>
          <span style="margin-left: 10px">{{ row.name }}</span>
        </template>
      </vxe-column>
      <vxe-column title="排序" width="180" align="center">
        <template #default="{ row }">
          <OrderPage :id="row.id" :data="initTableData" :list="list" :updateDataOrder="updateDataOrder" />
        </template>
      </vxe-column>
      <vxe-column  title="操作" width="280" align="center">
        <template #default="{ row }">
          <el-button @click="editorCategory(row.id)" type="text" size="small">编辑</el-button>
          <el-button @click="deleteCategory(row.id, row._index)" type="text" size="small">删除</el-button>
        </template>
      </vxe-column>
      <template v-slot:empty>
        <p class="emptynote">暂无数据</p>
      </template>
    </vxe-table>
    <!-- <el-table :data="tableData" style="width: 100%" v-loading="loading">
      <el-table-column prop="name" label="分类名称">
        <template slot-scope="scope">
          <i :class="'noselect icon iconfont ' + showIcon(scope.row.id, scope.row._index)"
            @click.stop="tiggleChildren(scope.row.id)"
            :style="'margin-left: '+rowMaringLeft(scope.row._index)+'px'"></i>
          <span style="margin-left: 10px">{{ scope.row.name }}</span>
        </template>
      </el-table-column>
      <el-table-column label="排序" width="180" align="center">
        <template slot-scope="scope">
          <OrderPage :id="scope.row.id" :data="initTableData" :updateDataOrder="updateDataOrder" />
        </template>
      </el-table-column>
      <el-table-column label="操作" width="280" align="center">
        <template slot-scope="scope">
          <el-button @click="editorCategory(scope.row.id)" type="text" size="small">编辑</el-button>
          <el-button @click="deleteCategory(scope.row.id, scope.row._index)" type="text" size="small">删除</el-button>
        </template>
      </el-table-column>
    </el-table> -->
    <SaveCategory ref="editCategory" :resetData='resetData' />
  </div>
</template>

<script>
import OrderPage from '@/components/main/user/system/category/common/OrderPage.vue'
import SaveCategory from '@/components/main/user/system/category/common/SaveCategory.vue'
export default {
  props: {
    dataTotal: {
      type: Function
    },
    system: {
      type: Object
    }
  },
  data () {
    return {
      loading: true,
      // 一开始获取到的表格数据
      initTableData: [],
      // 表格数据
      tableData: [],
      // 请求返回的数据
      data: []
    }
  },
  computed: {
    // 过滤数据
    list () {
      let list = []
      for (let i in this.initTableData) {
        list.push({
          id: this.initTableData[i].id,
          parentId: this.initTableData[i].parentId,
          orderNum: this.initTableData[i].orderNum,
          type: this.initTableData[i].type
        })
      }
      return list
    }
  },
  watch: {
    system: {
      handler (newValue) {
        if (newValue.id) {
          this.resetData()
        }
      },
      deep: true
    }
  },
  methods: {
    resetData () {
      if (this.system.id) {
        this.loading = true
        this.$post('/category/table-data-infos-by-system-id', { systemId: this.system.id }).then((response) => {
          this.loading = false
          this.dataTotal(response.total)
          if (response.total) {
            this.data = response.categories
            this.initTableData = this.tableData = initTablData(this.data)
          } else {
            this.data = []
            this.tableData = []
          }
        }, () => {
          this.loading = false
        })
      }
    },
    updateDataOrder (data, propid) {
      if (this.loading) {
        return
      }
      // 更新排序数据
      let updateData = []
      for (let k in data) {
        for (let i in this.data) {
          for (let j in this.data[i]) {
            let item = this.data[i][j]
            if (item.id === data[k].id) {
              item = JSON.parse(JSON.stringify(item))
              item.parentId = data[k].parentId
              item.orderNum = data[k].orderNum
              updateData.push(item)
            }
          }
        }
      }
      if (!updateData || updateData.length < 1) {
        return
      }
      this.loading = true
      // url 中增加 ${propid} 是为了确定写入日志对应的分类
      this.$jpost('/category/update-order/' + propid, updateData).then(response => {
        this.resetData()
      })
    },
    editorCategory (id) {
      let category
      for (let i in this.data) {
        for (let j in this.data[i]) {
          let item = this.data[i][j]
          if (item.id === id) {
            category = item
          }
        }
      }
      if (!category) {
        return
      }
      this.$refs['editCategory'].edit('编辑分类-' + category.name, this.system, category)
    },
    deleteCategory (id, index) {
      let category
      for (let i in this.data) {
        for (let j in this.data[i]) {
          let item = this.data[i][j]
          if (item.id === id) {
            category = item
          }
        }
      }
      if (!category) {
        return
      }
      let message = '确认要删除么？'
      let title = '提示'
      let type = 'warning'
      if (index === 2) {
        // 直接删除
      } else if (index === 1) {
        // 是否有子级
        if (hasChildren(category, this.data)) {
          message = '该分类下有子分类，如果点击确定会删除该分类以及所有的子分类，确认要删除么？'
          title = '注意'
          type = 'error'
        }
      } else if (index === 0) {
        // 是否有子级
        if (hasChildrenChildren(category, this.data)) {
          message = '该分类下有子分类，如果点击确定会删除该分类以及所有的子分类，确认要删除么？'
          title = '注意'
          type = 'error'
        }
      }
      this.$confirm(message, title, {
        type: type
      })
        .then(() => {
          this.$post('/category/delete-its-subclasses', {
            id: id
          }).then((response) => {
            if (response && response.length > 0) {
              this.resetData()
            }
          })
        })
        .catch(() => {
        })
    },
    showIcon (id, index) {
      // 如果没有子级则 icon-wendubukediao
      if (index === 2) {
        return 'icon-wendubukediao'
      }
      let item = getTableItemById(id, this.tableData)
      if (item._hasChildren) {
        if (item._childrenShow) {
          return 'icon-iconfontarrowdown'
        } else {
          return 'icon-iconfontplayfill'
        }
      }
    },
    rowMaringLeft (index) {
      if (index === 0) {
        return 0
      }
      let result = 15
      for (let i = 0; i < index; i++) {
        result += 15
      }
      return result
    },
    tiggleChildren (id) {
      // 控制子级是否显示
      let tableData = this.tableData
      for (let i in tableData) {
        if (tableData[i].id === id) {
          if (tableData[i]._hasChildren) {
            tableData[i]._childrenShow = !tableData[i]._childrenShow
          }
        }
      }
      // 如果 _childrenShow == false 则不加载子级
      let array = []
      for (let i in tableData) {
        if (tableData[i]._hasChildren) {
          array.push({
            id: tableData[i].id,
            _childrenShow: tableData[i]._childrenShow
          })
        }
      }
      let result = []
      let data = initTablData(this.data)
      let zzj = []
      for (let i in data) {
        let item = data[i]
        let bool = true
        let _childrenShow = item._childrenShow

        for (let j in array) {
          if (array[j].id === item.id) {
            _childrenShow = array[j]._childrenShow
            break
          }
          if (array[j].id === item.parentId && array[j]._childrenShow === false) {
            //  子级
            bool = false
            zzj.push(item.id)
          }
        }
        // 子子级
        if (zzj.indexOf(item.parentId) >= 0) {
          bool = false
        }
        if (!bool) {
          continue
        }
        item._childrenShow = _childrenShow
        result.push(item)
      }
      this.tableData = JSON.parse(JSON.stringify(result))
    }
  },
  components: {
    OrderPage,
    SaveCategory
  }
}

function initTablData (data) {
  let result = []
  let categories = data
  // 首先遍历父级ID为0的数据
  for (let i in categories[0]) {
    let item = categories[0][i]
    item._index = 0
    // 是否有子级
    if (categories.hasOwnProperty(item.id)) {
      item._hasChildren = true
      item._childrenShow = true
      // 加入结果集中
      result.push(item)
      // 遍历子级
      for (let j in categories[item.id]) {
        let ite = categories[item.id][j]
        ite._index = 1
        if (categories.hasOwnProperty(ite.id)) {
          ite._hasChildren = true
          ite._childrenShow = true
          result.push(ite)
          // 遍历子级
          for (let k in categories[ite.id]) {
            let it = categories[ite.id][k]
            it._index = 2
            if (categories.hasOwnProperty(it.id)) {
              it._hasChildren = true
              it._childrenShow = true
            } else {
              it._hasChildren = false
              it._childrenShow = false
            }
            result.push(it)
          }
        } else {
          ite._hasChildren = false
          ite._childrenShow = false
          result.push(ite)
        }
      }
    } else {
      item._hasChildren = false
      item._childrenShow = false
      // 加入结果集中
      result.push(item)
    }
  }
  return result
}

function getTableItemById (id, tableData) {
  for (let i in tableData) {
    if (tableData[i].id === id) {
      return tableData[i]
    }
  }
  return false
}

function getChildren (item, data) {
  let result = []
  for (let i in data) {
    for (let j in data[i]) {
      let temp = data[i][j]
      if (temp.parentId === item.id) {
        result.push(temp)
      }
    }
  }
  return result
}
function hasChildren (item, data) {
  for (let i in data) {
    for (let j in data[i]) {
      let temp = data[i][j]
      if (temp.parentId === item.id) {
        return true
      }
    }
  }
  return false
}

function hasChildrenChildren (item, data) {
  let childrenGroup = getChildren(item, data)
  if (!childrenGroup || childrenGroup.length < 1) {
    return false
  }
  return true
}

</script>
